<template>
  <div class="main">
    <img
      :src="showIcon"
      alt=""
      class="QRcodeIcon"
      @click="dingLogin"
      draggable="false"/>
    <a-form-model
      v-show="!dingShow"
      id="formLogin"
      ref="form"
      :model="form"
      :rules="rules"
      class="user-layout-login">
      <a-page-header title="用户登录" />
      <a-form-model-item prop="username">
        <a-input v-model="form.username" placeholder="账户: 123" size="large">
          <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)'}" type="user" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item prop="password">
        <a-input-password
          v-model="form.password"
          placeholder="密码"
          size="large">
          <a-icon slot="prefix" :style="{ color: 'rgba(0,0,0,.25)' }" type="lock" />
        </a-input-password>
      </a-form-model-item>
      <a-form-model-item prop="rememberMe">
        <a-checkbox :checked="form.rememberMe" @change="rememberMe">自动登录</a-checkbox>
      </a-form-model-item>
      <a-form-item style="margin-top:24px">
        <a-button
          :disabled="logining"
          :loading="logining"
          class="login-button"
          htmlType="submit"
          size="large"
          type="primary"
          @click="handleLogin"
        >确定
        </a-button>
      </a-form-item>
      <div class="user-login-other">
        <!--
          ruoyi后台不支持获取是否开启账户.
          故此处不做隐藏处理. 在ruoyi原前端中是在注册页面定义一个属性手动修改处理.
        -->
        <!--        <router-link class="register" :to="{ name: 'register' }">注册账户</router-link>-->
      </div>
    </a-form-model>
    <div v-show="dingShow" class="user-layout-login">
      <a-page-header title="钉钉扫码登录" />
      <span id="login_container" ref="loginContainer" />
    </div>
    <div style="position: absolute; z-index: 999; left: -30%; top: 10%;">
      <SliderVerify
        :height="height"
        :imgUrl="imgUrl"
        :isBorder="isBorder"
        :isCloseBtn="isCloseBtn"
        :isParentNode="isParentNode"
        :isReloadBtn="isReloadBtn"
        :isShowSelf.sync="showSelf"
        :width="width"
        @fail="verifyFail"
        @hide="hide"
        @reload="reload"
        @show="show"
        @success="verifySuccess"
      />
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getLoginParams } from '@/api/login'
import { LOGIN_USERNAME, LOGIN_PASSWORD, LOGIN_REMEMBERME } from '@/store/mutation-types'
import storage from 'store'
import dingTalkSetting from '@/store/modules/dingTalkSetting'
import allIcon from '@/core/icons'

export default {
  components: {},
  data () {
    return {
      // 外部图标库
      allIcon,
      // 二维码图标
      showIcon: 'https://img.alicdn.com/imgextra/i1/O1CN01a2J40d1HtlqT5oBD8_!!6000000000816-2-tps-204-204.png',
      // 全局钉钉配置
      DingSetting: dingTalkSetting,
      // 钉钉扫码展示
      dingShow: false,
      // 表单
      form: {
        username: '',
        password: '',
        rememberMe: true
      },
      rules: {
        username: [{ required: true, message: '请输入帐户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      // 按钮加载
      logining: false,
      // 钉钉登录开关
      dingLoginOnOff: true,
      // 验证码开关
      captchaOnOff: true,
      // 滑块验证码是否可见
      showSelf: false,
      // 滑块验证码宽度
      width: 300,
      // 滑块验证码高度
      height: 180,
      // 滑块验证码底部按钮
      isBorder: true,
      // 滑块验证码图片
      imgUrl: '',
      // 滑块验证码是否关闭
      isCloseBtn: true,
      // 滑块验证码是否刷新
      isReloadBtn: true,
      // 滑块验证码是否跟随父宽度
      isParentNode: false,
      // 滑块失败次数
      verifyLoginFail: 0
    }
  },
  created () {
    this.getStorage()
    this.getParams()
  },
  methods: {
    /** 登录配置 */
    getParams () {
      getLoginParams().then(res => {
        // 验证码开关
        this.captchaOnOff = res.captchaOnOff
        // 钉钉扫码登录开关
        this.dingLoginOnOff = res.dingLoginOnOff
        if (this.dingLoginOnOff) {
          this.ddLoginInit()
        }
      })
    },
    getStorage () {
      const username = storage.get(LOGIN_USERNAME)
      const password = storage.get(LOGIN_PASSWORD)
      const rememberMe = storage.get(LOGIN_REMEMBERME)
      if (username) {
        this.form = {
          username: username,
          password: password,
          rememberMe: rememberMe
        }
      }
    },
    /** 记住账号 */
    rememberMe (e) {
      this.form.rememberMe = e.target.checked
    },
    /** 登录按钮 */
    handleLogin () {
      if (this.captchaOnOff) {
        this.showSelf = true
      } else {
        this.loginSubmit()
      }
    },
    ...mapActions(['Login', 'Logout']),
    // 登录表单提交
    loginSubmit () {
      this.logining = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.logining = true
          if (this.form.rememberMe) {
            storage.set(LOGIN_USERNAME, this.form.username)
            storage.set(LOGIN_PASSWORD, this.form.password)
            storage.set(LOGIN_REMEMBERME, this.form.rememberMe)
          } else {
            storage.remove(LOGIN_USERNAME)
            storage.remove(LOGIN_PASSWORD)
            storage.remove(LOGIN_REMEMBERME)
          }
          this.Login(this.form)
            .then((res) => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              this.logining = false
            })
        } else {
          setTimeout(() => {
            this.logining = false
          }, 600)
        }
      })
    },
    // 登录成功回调
    loginSuccess () {
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
    },
    // 登录失败回调
    requestFailed (err) {
      this.form.code = undefined
      this.$notification.error({
        message: '登录提示',
        description: err,
        placement: 'topRight'
      })
    },
    /** 钉钉登录 */
    dingLogin () {
      if (this.dingLoginOnOff) {
        this.dingShow = !this.dingShow
        if (this.dingShow) {
          this.showIcon = 'https://img.alicdn.com/imgextra/i2/O1CN01yJNaqi1i2dWMOvg60_!!6000000004355-2-tps-204-204.png'
        } else {
          this.showIcon = 'https://img.alicdn.com/imgextra/i1/O1CN01a2J40d1HtlqT5oBD8_!!6000000000816-2-tps-204-204.png'
        }
      } else {
        this.$notification.warn({
          message: '登录提示',
          description: '未开启扫码登录',
          placement: 'topRight'
        })
      }
    },
    ddLoginInit () {
      // 钉钉扫码流程：扫码成功登录后会自动跳到这个url页面，url路径会携带code，你拿到这个code，调用登录接口成功就跳转。
      // 你的项目页面
      const url = encodeURIComponent(this.DingSetting.redirectUri)
      // 钉钉自己的url 修改上面俩，不需要动这个
      const goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + this.DingSetting.appKey + `&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}`)
      if (this.$refs.loginContainer) {
        DDLogin({
          id: 'login_container',
          goto: goto, // 请参考注释里的方式
          style: 'border:none;background-color:#FFFFFF;',
          width: '100%', // 官方参数 365
          height: '300'// 官方参数 400
        })
      }
      const handleMessage = (event) => {
        const origin = event.origin
        if (origin === 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
          const loginTmpCode = event.data
          // 获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          // 此步拿到临时loginTmpCode换取正式code
          window.location.href = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=' + this.DingSetting.appKey + `&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}&loginTmpCode=${loginTmpCode}`
        }
      }
      if (typeof window.addEventListener !== 'undefined') {
        window.addEventListener('message', handleMessage, false)
      } else if (typeof window.attachEvent !== 'undefined') {
        window.attachEvent('onmessage', handleMessage)
      }
    },
    reload () {
      console.log('SliderVerify => reload')
    },
    show () {
      console.log('SliderVerify => show')
    },
    hide () {
      console.log('SliderVerify => hide')
    },
    // 滑块验证码成功
    verifySuccess () {
      this.showSelf = false
      this.loginSubmit()
    },
    // 滑块验证码失败
    verifyFail () {
      this.verifyLoginFail = this.verifyLoginFail + 1
      if (this.verifyLoginFail > 10) {
        this.showSelf = false
        this.$notification.open({
          message: '系统提示',
          description: '验证过不去就休息会儿吧，你都错了' + this.verifyLoginFail + '次了',
          icon: h => {
            return h(
              'a-icon',
              {
                props: {
                  type: 'alert'
                }
              }
            )
          }
        })
      }
    }
  }
}
</script>

<style lang='less' scoped>
.QRcodeIcon {
  position: absolute;
  right: 0;
  width: 64px;
}

.ant-space-align-center {
  color: #8f959e;
  line-height: 30px;
  height: 30px;
}

.user-layout-login label {
  font-size: 12px !important;
}

.user-layout-login {
  label {
    font-size: 14px;
  }

  .ant-page-header {
    padding: 60px 0 45px 0;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
    border-radius: 4px;
  }
}
</style>
